﻿Imports NewHeaderSystems.Archive.Engine
Imports NewHeaderSystems.Archive.Core
Imports NewHeaderSystems.Archive.Data
Imports System.Collections.Generic

Public Class Search
    Inherits PageTemplate

    Private WithEvents _checkBoxHeader As New DatagridViewCheckBoxHeaderCell

    Private Const MAX_ROWS As Integer = 100

    Private Const COLUMN_ID As String = "colID"
    Private Const COLUMN_PRINT As String = "colPrint"

    Private Sub DoSearch()
        Me.ParentForm.Cursor = Cursors.WaitCursor
        btnViewConfirm.Enabled = False
        Dim totalRowCount As Integer
        Dim confirmsView As List(Of ConfirmView) = DataScript.GetSearchResults(chkArchiveDate.Checked, dtArchiveDateFrom.Value, dtArchiveDateTo.Value, _
                                                    chkTradeDate.Checked, dtTradeDateFrom.Value, dtTradeDateTo.Value, _
                                                    txtAccountID.Text, txtCustodianAccountID.Text, txtTicker.Text, txtCusip.Text, _
                                                    GetSearchValue(cboSource.Text), GetSearchValue(cboTransactionType.Text), txtDtcControlNumber.Text, txtExecBrokerNumber.Text, chkUnassigned.Checked, Nothing, MAX_ROWS, totalRowCount)

        Dim bs As New BindingSource
        bs.DataSource = New SortableBindingList(Of ConfirmView)(confirmsView)
        confirmsGrid.DataSource = bs
        confirmsGrid.Columns(COLUMN_PRINT).HeaderCell = _checkBoxHeader

        ShowSummary(totalRowCount)

        Me.ParentForm.Cursor = Cursors.Default
        confirmsGrid.Focus()
    End Sub

    Private Sub btnSearch_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSearch.Click
        DoSearch()
    End Sub

    Private Sub chkTradeDate_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles chkTradeDate.CheckedChanged
        RefreshTradeDates(chkTradeDate.Checked)
    End Sub

    Private Sub RefreshTradeDates(ByVal enabled As Boolean)
        dtTradeDateFrom.Enabled = enabled
        dtTradeDateTo.Enabled = enabled
    End Sub

    Private Sub chkArchiveDate_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles chkArchiveDate.CheckedChanged
        RefreshArchiveDates(chkArchiveDate.Checked)
    End Sub

    Private Sub RefreshArchiveDates(ByVal enabled As Boolean)
        dtArchiveDateFrom.Enabled = enabled
        dtArchiveDateTo.Enabled = enabled
    End Sub

    Private Sub ResetForm()
        chkTradeDate.Checked = False
        chkArchiveDate.Checked = False
        chkUnassigned.Checked = False
        txtAccountID.Text = ""
        txtCusip.Text = ""
        txtCustodianAccountID.Text = ""
        txtDtcControlNumber.Text = ""
        txtExecBrokerNumber.Text = ""
        txtTicker.Text = ""
        confirmsGrid.Rows.Clear()
        txtAccountID.Focus()
        cboTransactionType.SelectedIndex = 0 'Select the first term 'All'
        cboSource.SelectedIndex = 0 'Select the first item 'All'
        lblResultSummary.Visible = False
        btnViewConfirm.Enabled = False
    End Sub

    Private Sub ShowSummary(ByVal resultCount As Integer)
        Dim message As String
        If resultCount = 0 Then
            message = "Your search did not return any results."
        Else
            message = String.Format("{0} confirms were found", resultCount)
            If (resultCount > MAX_ROWS) Then
                message += String.Format(", the first {0} are shown below.", MAX_ROWS)
            End If
        End If
        lblResultSummary.Text = message
        lblResultSummary.Visible = True
    End Sub

    Private Sub btnNewSearch_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnNewSearch.Click
        ResetForm()
    End Sub

    Private Sub Search_PageLeave(ByVal sender As System.Object, ByVal e As Microsoft.Samples.Windows.Forms.Navigation.PageEventArgs) Handles MyBase.PageLeave
        Me.ParentForm.AcceptButton = Nothing
        Me.ParentForm.CancelButton = Nothing
    End Sub

    Private Sub ShowConfirm()
        If confirmsGrid.SelectedCells.Count > 0 Then
            Dim row As DataGridViewRow = confirmsGrid.Rows(confirmsGrid.SelectedCells(0).RowIndex)
            Dim confirm As ConfirmView = DirectCast(row.DataBoundItem, ConfirmView)
            Dim frm As New ConfirmViewer
            frm.LoadConfirm(confirm.ID)
            frm.ShowDialog()
        End If
    End Sub

    Private Sub confirmsGrid_KeyUp(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles confirmsGrid.KeyUp
        Dim tag As String = ""
        If Not confirmsGrid.Tag Is Nothing Then
            tag = confirmsGrid.Tag.ToString()
        End If

        confirmsGrid.Tag = ""
        If e.KeyData = Keys.Enter And tag = "SHOW" Then
            ShowConfirm()
        End If
    End Sub

    Private Sub confirmsGrid_KeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles confirmsGrid.KeyDown
        If e.KeyData = Keys.Enter Then
            e.Handled = True 'Prevent the focus going to the next row
            confirmsGrid.Tag = "SHOW"
        End If
    End Sub


    Private Sub Search_Enter(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Enter
        ResetForm()
        Me.ParentForm.AcceptButton = btnSearch
        Title = "Search"
        Description = "Search for confirms that have been previously archived. Enter in your search criteria and click on the search button."
        PageIcon = My.Resources.Find

    End Sub

    Private Sub Search_Leave(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Leave
        Me.ParentForm.AcceptButton = Nothing
    End Sub

    Private Sub btnViewConfirm_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnViewConfirm.Click
        ShowConfirm()
    End Sub

    Private Sub confirmsGrid_SelectionChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles confirmsGrid.SelectionChanged
        btnViewConfirm.Enabled = confirmsGrid.SelectedCells.Count > 0
    End Sub

    Public Sub New()

        ' This call is required by the Windows Form Designer.
        InitializeComponent()

        ' Add any initialization after the InitializeComponent() call.
        LoadDropDowns()
    End Sub

    Private Sub chkHeader_OnCheckBoxClicked(ByVal state As Boolean) Handles _checkBoxHeader.OnCheckBoxClicked
        For Each row As DataGridViewRow In confirmsGrid.Rows
            row.Cells(COLUMN_PRINT).Value = state 'NOTE: Using the enumerator for colPrint doesn't seem to work here. Using column name works.
        Next
        confirmsGrid.EndEdit() 'Fixes bug where first row checkbox is not refreshed on screen.
    End Sub

    Private Sub DoPrint()
        Dim confirmsList() As Integer = GetConfirmsListToPrint()
        If confirmsList.Count = 0 Then
            MessageBox.Show("No confirms selected. Please select one or more confirms to print.", "No confirms selected", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
        Else
            Me.ParentForm.Cursor = Cursors.WaitCursor
            Dim report = GetReport(confirmsList)
            Me.ParentForm.Cursor = Cursors.Default
            ShowPrintPreview(report)
        End If
    End Sub

    Private Function GetConfirmsListToPrint() As Integer()
        Dim list As New List(Of Integer)
        For Each row As DataGridViewRow In confirmsGrid.Rows
            If Not row.Cells(COLUMN_PRINT).Value Is Nothing AndAlso Boolean.Parse(row.Cells(COLUMN_PRINT).Value.ToString()) = True Then
                list.Add(Integer.Parse(row.Cells(COLUMN_ID).Value.ToString()))
            End If
        Next
        Return list.ToArray()
    End Function

    Private Function GetReport(ByVal confirmsList As Integer()) As String
        Dim confirmCreator As New ConfirmRenderer
        Return confirmCreator.Render(confirmsList, "<:NEWPAGE>")
    End Function

    Private Sub ShowPrintPreview(ByVal report As String)
        Dim print = New PrintHelper
        Dim preview = PrintHelper.PrintPreview.Print
        If MessageBox.Show("Do you want to see a preview of the confirms?", "Print Preview", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) = DialogResult.Yes Then
            preview = PrintHelper.PrintPreview.Preview
        End If

        print.PrintOrPreview(PrintHelper.CharsPerLine.CPL80, _
           report, "", "", preview, _
           PrintHelper.PrintOrientation.Portrait)
    End Sub

    Private Sub confirmsGrid_CellMouseDoubleClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellMouseEventArgs) Handles confirmsGrid.CellMouseDoubleClick
        If e.RowIndex > 0 And e.ColumnIndex <> confirmsGrid.Columns(COLUMN_PRINT).Index Then 'Ignore header and check box columns
            ShowConfirm()
        End If
    End Sub

    Private Sub LoadDropDowns()
        cboTransactionType.Items.Add("All")
        cboTransactionType.Items.AddRange(DataScript.GetTransactionTypes().ToArray())
    End Sub

    Private Sub btnPrint_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnPrint.Click
        DoPrint()
    End Sub

    Private Function GetSearchValue(ByVal text As String) As String
        If text = "All" Then 'The search procedure expects string.empty to ignore a search field.
            Return String.Empty
        Else
            Return text
        End If
    End Function

    Private Sub txtTicker_Leave(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtTicker.Leave
        txtTicker.Text = txtTicker.Text.ToUpper()
    End Sub
End Class
